<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择分类" clearable>
          <el-option
            v-for="dict in dict.type.community_suggestion_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['suggestion:suggestion:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['suggestion:suggestion:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['suggestion:suggestion:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['suggestion:suggestion:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="suggestionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="内容" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="showContent(scope.row.content, scope.row.remark)">详情></el-button>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="category">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.community_suggestion_category" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span :style="getStatusStyle(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </span>
        </template>
      </el-table-column>
      <!-- 管理员可见的备注列 -->
      <el-table-column
        v-if="isAdmin"
        label="备注"
        align="center"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div v-if="isAdmin">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['suggestion:suggestion:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['suggestion:suggestion:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleReview(scope.row)"
              v-hasPermi="['suggestion:suggestion:review']"
            >审核</el-button>
          </div>
          <div v-else>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-thumb-up"
              :style="{color: scope.row.myVote === 1 ? '#409EFF' : ''}"
              @click="handleVote(scope.row, 1)"
            >支持</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-thumb-down"
              :style="{color: scope.row.myVote === -1 ? '#F56C6C' : ''}"
              @click="handleVote(scope.row, -1)"
            >反对</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-chat-dot-round"
              @click="handleComment(scope.row)"
            >评论</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改社区建议对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192" />
          <el-button
            type="primary"
            icon="el-icon-microphone"
            size="mini"
            @click="startVoiceRecognition"
            style="margin-top: 10px;"
          >
            语音输入
          </el-button>
        </el-form-item>


        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
              v-for="dict in dict.type.community_suggestion_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 管理员可见的备注编辑 -->
        <el-form-item v-if="isAdmin" label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 内容详情对话框 -->
    <el-dialog :title="contentDialogTitle" :visible.sync="contentDialogVisible" width="500px" append-to-body>
      <div v-html="currentContent"></div>
      <div v-if="currentRemark" class="remark-section">
        <h4>审核备注：</h4>
        <p>{{ currentRemark }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="contentDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog :title="reviewTitle" :visible.sync="reviewOpen" width="500px" append-to-body>
      <el-form ref="reviewForm" :model="reviewForm" :rules="reviewRules" label-width="80px">
        <el-form-item label="状态" prop="status">
          <el-select v-model="reviewForm.status" placeholder="请选择状态">
            <el-option label="待定" value="pending"></el-option>
            <el-option label="已批准" value="approved"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
            <el-option label="已实施" value="implemented"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="reviewForm.remark"
            type="textarea"
            placeholder="请输入审核备注"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReviewForm">确 定</el-button>
        <el-button @click="cancelReview">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 评论侧边栏 -->
    <el-drawer
      title="评论详情"
      :visible.sync="commentDrawerVisible"
      direction="rtl"
      size="40%"
      :before-close="handleDrawerClose">
      <div class="drawer-content">
        <div class="suggestion-detail">
          <h3>{{ currentSuggestion.title }}</h3>
          <div v-html="currentSuggestion.content"></div>
        </div>
        <div class="comment-section">
          <div class="comment-list">
            <div
              v-for="comment in commentList"
              :key="comment.id"
              class="comment-item"
            >
              <div class="comment-header">
                <span class="user">用户{{ comment.userId }}</span>
                <span class="time">{{ comment.createTime }}</span>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <el-button
                size="mini"
                @click="handleReply(comment)"
              >回复</el-button>
              <div v-if="comment.children && comment.children.length">
                <div
                  v-for="child in comment.children"
                  :key="child.id"
                  class="child-comment"
                >
                  <div class="comment-header">
                    <span class="user">用户{{ child.userId }}</span>
                    <span class="time">{{ child.createTime }}</span>
                  </div>
                  <div class="comment-content">
                    @{{ comment.userId }} {{ child.content }}
                  </div>
                  <el-button
                    size="mini"
                    @click="handleReply(child)"
                  >回复</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="comment-input">
          <el-input
            type="textarea"
            v-model="newComment"
            :placeholder="replyTo ? `回复用户${replyTo.username}:` : '请输入评论内容'"
            rows="3"
          ></el-input>
          <div class="action-bar">
            <span v-if="replyTo" class="reply-info">
              回复用户{{ replyTo.username }}
              <el-button type="text" @click="cancelReply">取消回复</el-button>
            </span>
            <el-button
              type="primary"
              size="mini"
              @click="submitComment"
            >发布</el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listSuggestion, getSuggestion, delSuggestion, addSuggestion, updateSuggestion } from "@/api/suggestion/suggestion";
import { addVote, delVote } from "@/api/suggestion/vote";
import { getInfo } from "@/api/login";
import { listComment, addComment } from "@/api/suggestion/comment";

export default {
  name: "Suggestion",
  dicts: ['community_suggestion_category', 'community_suggestion_status'],
  data() {
    return {
      currentRemark: '',
      commentDrawerVisible: false,
      currentSuggestion: {},
      commentList: [],
      newComment: '',
      replyTo: null,
      currentUser: {},
      isAdmin: false,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      suggestionList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        title: null,
        content: null,
        category: null,
        status: null,
        viewCount: null,
        earnedPoints: null,
      },
      form: {},
      rules: {
        title: [
          {required: true, message: "标题不能为空", trigger: "blur"},
          {max: 20, message: "标题长度不能超过20个字符", trigger: "blur"}
        ],
        content: [
          {required: true, message: "内容不能为空", trigger: "blur"}
        ],
        category: [
          {required: true, message: "分类不能为空", trigger: "change"}
        ],
      },
      contentDialogVisible: false,
      contentDialogTitle: '内容详情',
      currentContent: '',
      reviewOpen: false,
      reviewTitle: "",
      reviewForm: {
        id: null,
        status: null,
        remark: null,
      },
      reviewRules: {
        status: [
          {required: true, message: "状态不能为空", trigger: "change"}
        ],
        remark: [
          {required: true, message: "请输入审核备注", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.loadUserInfo();
    this.getList();
  },
  methods: {
    startVoiceRecognition() {
      if (!('webkitSpeechRecognition' in window)) {
        this.$message.error('当前浏览器不支持语音识别，请使用 Chrome 浏览器');
        return;
      }

      navigator.mediaDevices.getUserMedia({ audio: true })
        .then(() => {
          if (this.isRecognizing) {
            this.$message.warning('语音识别正在进行中');
            return;
          }

          const recognition = new webkitSpeechRecognition();
          recognition.lang = 'zh-CN'; // 中文识别
          recognition.interimResults = false;
          recognition.maxAlternatives = 1;
          recognition.continuous = false; // 非连续识别

          this.isRecognizing = true;

          recognition.start();
          this.$message.info('请开始讲话...');

          recognition.onresult = (event) => {
            const transcript = event.results[0][0].transcript;
            this.form.content = (this.form.content || '') + transcript;
            this.$message.success('语音识别完成');
          };

          recognition.onerror = (event) => {
            console.error('语音识别错误:', event);
            this.$message.error(`语音识别出错: ${event.error}`);
          };

          recognition.onend = () => {
            console.log('语音识别结束');
            this.isRecognizing = false;
          };
        })
        .catch((err) => {
          console.error('麦克风权限错误:', err);
          this.$message.error('麦克风访问被拒绝或出错');
        });
    },
    // 加载用户信息并检查权限
    async loadUserInfo() {
      try {
        const res = await getInfo();
        this.currentUser = res.user;
        // 检查是否是管理员（roleId为1或包含admin角色）
        this.isAdmin = res.roles.includes('admin') || (res.roleIds && res.roleIds.includes(1));
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },

    // 其他方法保持不变...
    async handleComment(row) {
      this.currentSuggestion = row;
      this.commentDrawerVisible = true;
      await this.loadComments(row.id);
    },

    async loadComments(suggestionId) {
      try {
        const res = await listComment({suggestionId});
        const comments = res.rows;

        const commentMap = {};
        const rootComments = [];

        comments.forEach(comment => {
          comment.children = [];
          commentMap[comment.id] = comment;
        });

        comments.forEach(comment => {
          if (comment.parentId && commentMap[comment.parentId]) {
            commentMap[comment.parentId].children.push(comment);
          } else {
            rootComments.push(comment);
          }
        });

        this.commentList = [...rootComments];
      } catch (error) {
        console.error("加载评论失败:", error);
      }
    },

    handleReply(comment) {
      this.replyTo = comment;
    },

    cancelReply() {
      this.replyTo = null;
    },

    async submitComment() {
      if (!this.newComment.trim()) return;

      try {
        const commentData = {
          suggestionId: this.currentSuggestion.id,
          userId: this.currentUser.userId,
          content: this.newComment,
          parentId: this.replyTo?.id || null
        };

        await addComment(commentData);
        this.$modal.msgSuccess("评论成功");
        this.newComment = '';
        this.replyTo = null;
        await this.loadComments(this.currentSuggestion.id);
      } catch (error) {
        this.$modal.msgError("评论失败：" + error.message);
      }
    },

    handleDrawerClose() {
      this.commentDrawerVisible = false;
      this.currentSuggestion = {};
      this.commentList = [];
      this.newComment = '';
      this.replyTo = null;
    },

    async handleVote(row, voteType) {
      try {
        if (row.myVote === voteType) {
          await this.handleCancelVote(row);
          return;
        }

        await this.$modal.confirm(`确定要${voteType === 1 ? '支持' : '反对'}该建议吗？`);

        const voteData = {
          suggestionId: row.id,
          userId: this.currentUser.userId,
          voteType: voteType
        };

        await addVote(voteData);

        const originalVote = row.myVote;
        row.myVote = voteType;

        if (voteType === 1) {
          row.upVotes += 1;
          if (originalVote === -1) row.downVotes -= 1;
        } else {
          row.downVotes += 1;
          if (originalVote === 1) row.upVotes -= 1;
        }

        this.$modal.msgSuccess(originalVote ? "投票修改成功" : "投票成功");
      } catch (error) {
        if (error !== 'cancel') {
          console.error('投票失败:', error);
          this.$modal.msgError("投票失败");
        }
      }
    },

    async handleCancelVote(row) {
      try {
        await this.$modal.confirm("确定要取消投票吗？");
        await delVote({
          suggestionId: row.id,
          userId: this.currentUser.userId
        });

        if (row.myVote === 1) row.upVotes -= 1;
        if (row.myVote === -1) row.downVotes -= 1;
        row.myVote = null;

        this.$modal.msgSuccess("已取消投票");
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消投票失败:', error);
          this.$modal.msgError("取消投票失败");
        }
      }
    },

    getList() {
      this.loading = true;
      listSuggestion(this.queryParams).then(response => {
        console.log(response);
        this.suggestionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.form = {
        id: null,
        userId: null,
        title: null,
        content: null,
        category: null,
        status: null,
        viewCount: null,
        earnedPoints: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加社区建议";
    },

    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSuggestion(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改社区建议";
      });
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSuggestion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSuggestion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除社区建议编号为"' + ids + '"的数据项？').then(function () {
        return delSuggestion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    handleReview(row) {
      this.resetReview();
      this.reviewForm.id = row.id;
      this.reviewOpen = true;
      this.reviewTitle = "审核社区建议";
    },

    submitReviewForm() {
      this.$refs["reviewForm"].validate(valid => {
        if (valid) {
          updateSuggestion(this.reviewForm).then(response => {
            this.$modal.msgSuccess("审核成功");
            this.reviewOpen = false;
            this.getList();
          });
        }
      });
    },

    cancelReview() {
      this.reviewOpen = false;
      this.resetReview();
    },

    resetReview() {
      this.reviewForm = {
        id: null,
        status: null,
        remark: null,
      };
      this.resetForm("reviewForm");
    },

    handleExport() {
      this.download('suggestion/suggestion/export', {
        ...this.queryParams
      }, `suggestion_${new Date().getTime()}.xlsx`)
    },

    getStatusText(status) {
      switch (status) {
        case 'pending':
          return '待定';
        case 'approved':
          return '已批准';
        case 'rejected':
          return '已拒绝';
        case 'implemented':
          return '已实施';
        default:
          return '未知状态';
      }
    },

    getStatusStyle(status) {
      switch (status) {
        case 'pending':
          return {color: 'orange'};
        case 'approved':
          return {color: 'green'};
        case 'rejected':
          return {color: 'red'};
        case 'implemented':
          return {color: 'blue'};
        default:
          return {};
      }
    },

    showContent(content, remark) {
      this.currentContent = content;
      this.currentRemark = remark || '';
      this.contentDialogVisible = true;
    }
  }
};
</script>

<style scoped>
.el-button [class*=el-icon-] + span {
  margin-left: 3px;
}

.drawer-content {
  padding: 20px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.suggestion-detail {
  flex: 0 0 40%;
  overflow-y: auto;
  padding: 15px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.comment-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.comment-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.comment-item {
  margin-bottom: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.child-comment {
  margin: 10px 0 0 20px;
  padding: 8px;
  background: #fff;
  border-left: 3px solid #409EFF;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
  color: #666;
}

.comment-content {
  font-size: 14px;
  line-height: 1.5;
}

.comment-input {
  flex-shrink: 0;
  border-top: 1px solid #eee;
  padding-top: 20px;
  background: white;
  z-index: 1;
}

.action-bar {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reply-info {
  font-size: 12px;
  color: #666;
}

.remark-section {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
